package com.ok.common.utils

import android.os.Build
import android.os.Environment
import com.ok.common.base.AppContext
import java.io.File
import java.io.IOException

object FileUtils {

    fun isSDCardExists(): Boolean {
        val statusStr = Environment.getExternalStorageState()
        return Environment.MEDIA_MOUNTED == statusStr
    }

    fun getFile(): File {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            AppContext.filesDir
        } else {
            return if (isSDCardExists()) {
                Environment.getExternalStorageDirectory()
            } else {
                Environment.getDataDirectory()
            }
        }
    }

    fun getFile(dirName: String): File? {
        val file = File(getFile(), dirName)
        if (!file.exists()) {
            return null
        }
        return file
    }

    fun createFile(fileName: String, dirName: String): File? {
        val apkDir = File(getFile(), dirName)
        if (!apkDir.exists()) {
            apkDir.mkdirs()
        }
        val tempFile = File(apkDir, fileName)
        try {
            if (tempFile.exists()) {

                tempFile.delete()
            }
            tempFile.createNewFile()
        } catch (e: IOException) {
            e.printStackTrace()
            return null
        }
        return tempFile
    }

    fun deleteFile(file: File): Boolean {
        return file.delete()
    }

    fun deleteFile(filePath: String): Boolean {
        val file = File(filePath)
        return file.delete()
    }

}
